<template>
  <el-dialog v-model="visible" title="选择城市" :close-on-click-modal="false">
    <el-tree
      ref="tree2Ref"
      :data="areaTreeData"
      node-key="areaId"
      :filter-node-method="filterNode"
      :props="props"
      :expand-on-click-node="false"
       show-checkbox
       @check-change="handleCheckChange"
       :default-checked-keys="checkedKeys"
       :check-strictly="true"
    >
      <template #default="{ node, data }">
        <span class="addr-name">{{ node.label }}</span>
      </template>
    </el-tree>
  </el-dialog>
</template>

<script setup>
import { treeDataTranslate } from '@/utils'
//const resourcesUrl = import.meta.env.VITE_APP_RESOURCES_URL;
const emit = defineEmits(["refreshDataList"]);
const visible = ref(false);

const checkedKeys = ref([]);
var obj=null;
const init = (selectedNode) => {
    obj = selectedNode;
  getDataList();
};

defineExpose({ init });

const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const areaTreeData = ref(null)
const getDataList = () => {
  visible.value = true;  
  http({
    url: http.adornUrl('/admin/area/list'),
    method: 'get',
    params: http.adornParams(Object.assign({
      current: page.currentPage,
      size: page.pageSize
    }, {

    }))
  }).then(({ data }) => {
    areaTreeData.value = treeDataTranslate(data, 'areaId', 'parentId')

    //禁用父节点
    areaTreeData.value.forEach(function(value) {
        traverseTree(value,disabledNode);
    });

    checkedKeys.value=obj.map(function(num) {
        return num.areaId;
    });
  })
}

const traverseTree = (node, callback) => {
    // 对当前节点执行回调函数
    callback(node);
 
    // 遍历所有子节点
    if (node.children) {
        node.children.forEach(function(child) {
            traverseTree(child, callback); // 递归遍历每个子节点
        });
    }
}

/**
 * 禁用父节点
 */
/*const disabledNode = (node) => {
    if(node.children != null){
        node.disabled = true;
    }
}*/

/**
 * 只选择省份
 */
const disabledNode = (node) => {
    if(node.level != 1){
        node.disabled = true;
    }
}

const filterNode = (value, data) => {
  if (!value) return true
  return data.areaName.indexOf(value) !== -1
}

const props = {
  id: 'areaId',
  label: 'areaName',
  children: 'children'
}

const handleCheckChange = (data,checked,indeterminate) => {
    console.log(data, checked, indeterminate)
    if(checked){
        //选中
        obj.push({"areaId": data.areaId,"areaName": data.areaName,"parentId":  data.parentId,"level": data.level,"areas": data.areas});
    }else{
        let index = obj.findIndex(item => item.areaId === data.areaId);
        if (index !== -1) {
            obj.splice(index, 1);
        }
    }
}
</script>
